$(document).ready(function () {
    $("body").append("<div id='MultiPostSelect_Panel'  style='position:absolute; z-index:10001;'></div>");
    $(document).click(function (event) {
        var element = event.target;
        var emeCls = $(element).attr("bj");
        if (emeCls != "cBj") {
            $("#MultiPostSelect_Panel").css("display", "none");
        }
    });
});

// ----------------------------------------
// 部门选择器
// ----------------------------------------
(function ($) {
    $.fn.MultiPostSelectCtrl = function (options) {

        //(this).attr('bj','cBj');
        var defaults = {
            CtrolID: $(this).attr("id"),
            //evt: "click",
            divItemSelect: 'div_item_select',
            showDataDivId: "MultiPostSelect_Panel",
            inputDataTextId: "input_text"
        };
        if (options) {
            $.extend(defaults, options);
        }
        //初始化控件
        //添加对应样式
        var SelectMode = $(this).attr("SelectMode") == "s";
        var Event = $(this).attr("event");


        $(this).wrap("<div id=\"Dept_" + defaults.CtrolID + "\" class=\"deptctrl\" style=\"width:" + (this.width() + 20) + "px\"></div>");
        $(this).width(this.width() - 16);
        $(this).after('<input type="button" class="button" id="btn_' + defaults.CtrolID + '"/>');
        $("#btn_" + defaults.CtrolID).click(function (event) {
            fn($("#" + defaults.CtrolID).val(), event);
        })
        //$("body").append("<div id='div_tree_" + defaults.CtrolID + "' style='position:absolute; z-index:10001;display:none'><ul id='tree_" + defaults.CtrolID + "' class='ztree'></ul><div>");
        $("body").append("<div id='div_tree_" + defaults.CtrolID + "' style='position:absolute; z-index:10001;display:none;background-color: #F5FFFA;\"" + (!SelectMode ? "border:1px solid #ccc; bgcolor:#eee;'><div style=\"background-color: #F5FFFA;\"><input type=\"button\" value=\"确定\" id='btn" + defaults.CtrolID + "_OK'/><input type=\"button\" value=\"取消\" btn" + defaults.CtrolID + "_Cancel'/></div>" : "'>") + "<ul id='tree_" + defaults.CtrolID + "' class='ztree' style=\"margin-top:0px;\"></ul><div>");


        $("#btn" + defaults.CtrolID + "_OK").click(function (event) {
            var sItems = $.fn.zTree.getZTreeObj("tree_" + defaults.CtrolID).getSelectedNodes();
            var _v = "";
            var _t = "";
            $.each(sItems, function (i) {
                if (sItems[i].nodetype == "3e") {
                    _v = (_v == "") ? sItems[i].id : (_v + "," + sItems[i].id);
                    _t = (_t == "") ? sItems[i].name.split("(")[0] : (_t + "," + sItems[i].name.split("(")[0]);
                }
            });
            setValue(_v);
            setText(_t);
            if (Event != "") {
                eval(Event);
            }

        })


        /* 树 */
        var setting = {
            view: {
                selectedMulti: !SelectMode
            },
            check: {
                enable: true,
                chkboxType: { "Y": "ps", "N": "ps" }
            },
            data: {
                key: {
                    title: "t"
                },
                simpleData: {
                    enable: true
                }
            },
            callback: {
                beforeClick: beforeClick,
                onClick: onClick
            }
        };
        var log, className = "dark";
        function beforeClick(treeId, treeNode, clickFlag) {
            className = (className === "dark" ? "" : "dark");
            //showLog("[ " + getTime() + " beforeClick ]&nbsp;&nbsp;" + treeNode.name);
            return (treeNode.click != false);
        }
        _treeNode = null;
        function onClick(event, treeId, treeNode, clickFlag) {
            //debugger
            _treeNode = treeNode;
            //$("#" + defaults.CtrolID).val(treeNode.name);
            //debugger
            if (treeNode.IsLoaded == 'true') {
                return;
            }
            else if (treeNode.flag == '1d') {
                treeNode.IsLoaded = "true";
                getUserData();
            }
            //setValue(treeNode.id);
            //hide();
        }

        function onNodeCheck(e, treeId, treeNode, CtrlID) {
            var zTree = $.fn.zTree.getZTreeObj("treeDemo"),
	            nodes = zTree.getCheckedNodes(true),
	            v = "";
            for (var i = 0, l = nodes.length; i < l; i++) {
                v += nodes[i].name + ",";
            }
            if (v.length > 0) v = v.substring(0, v.length - 1);
            var cityObj = $("#citySel");
            cityObj.attr("value", v);
        }


        //------------------------------
        _CtrlID = "tree_" + defaults.CtrolID;
        _Data = null;
        function getUserData() {
            var deptID = _treeNode.id;
            $.get("/Extend/AjaxData/DataTableJsonList.aspx?entity=V_PostData&type=0&condition=DeptID='" + deptID + "'",
            function (d, t) {
                //debugger
                if (d == '{"total":0,"rows":}') {
                    return;
                }
                var data = eval("(" + d + ")");
                var temp = [];
                $.each(data.rows, function (e) {
                    //debugger
                    AddNewNode(data.rows[e].id, data.rows[e].name, data.rows[e].DutyName, _CtrlID);
                });
            });
        }


        function GetData(entity, condition) {
            if (_Data == null) {
                $.ajax({
                    type: "GET",
                    url: "/Extend/AjaxData/DataTableJsonList.aspx",
                    data: { entity: entity, condition: condition },
                    async: false,
                    success: function (data) {
                        //debugger
                        if (data == '{"total":0,"rows":}') {
                            return;
                        }
                        else {
                            _Data = eval("(" + data + ")");
                        }
                    },
                    error: function (e) {
                        return;
                    }
                }
              );
            }
            if (_Data != null) {
                $.fn.zTree.init($("#tree_" + defaults.CtrolID), setting, _Data.rows);
            }
        }
        GetData($(this).attr("entity"), $(this).attr("condition"));
        var obj = defaults.CtrolID;
        //$.fn.zTree.init($("#tree_" + defaults.CtrolID), setting, Org.rows);
        var obj = defaults.CtrolID;

        //在页面上显示用户选择界面
        function showPanel() {
            var tLeft = $("#" + obj).offset().left;
            var tTop = $("#" + obj).offset().top + 10;
            $("#div_tree_" + defaults.CtrolID).css({ display: "block", left: tLeft, top: tTop });
        }

        $(document).click(function (event) {
            var element = event.target;
            var id = $(element).attr("id");
            if (id == undefined || id == null) {
                hide();
            }
            else if (id.indexOf("tree_" + defaults.CtrolID) < 0) {
                hide();
            }
        });



        //生成部门信息
        function carHtml(vYear, vMonth, vDay, vipt) {

        }

        //设置选择的值
        function setValue(value) {
            $("#" + defaults.CtrolID).attr("SValue", value);
        }
        function setText(text) {
            $("#" + defaults.CtrolID).attr("SText", text);
            $("#" + defaults.CtrolID).val(text);
        }
        function getValue(value) {
            return $("#" + defaults.CtrolID).attr("SValue");
        }

        function getText(value) {
            return $("#" + defaults.CtrolID).val();
        }
        $(this).click(function (event) {
            fn(this.value, event);
        });
        //绑定键盘事件
        $(this).keyup(function (event) {
            fn(this.value, event);
        });

        function fn(v, event) {
            if (event.keyCode == 40) {//down
                chageSelect(1);
            }
            else if (event.keyCode == 38) {//up
                chageSelect(-1);
            }
            else if (event.keyCode == 13) {//回车
                item_click($("#" + defaults.showDataDivId + " div[class='" + defaults.divItemSelect + "']"));
            }
            else if (v.length >= 0) {
                //registerInputEvent();
                setTimeout(showPanel, 0);
            }
            else {
                $("#div_tree_" + defaults.CtrolID).slideUp(200);
            }
        }
        function hide() {
            $("#div_tree_" + defaults.CtrolID).css("display", "none");
        }

    }
})(jQuery);

var CtrlID = "", //
    _treeNode = null;
function AddNewNode(id, name, postName, ctrlID) {
    var zTree = $.fn.zTree.getZTreeObj(ctrlID);
    //debugger
    zTree.addNodes(_treeNode, { id: id, pId: _treeNode.id, name: name + "(" + postName + ")", nodetype: "3e", checked: true, icon: "/images/b.png" });
    var nodes = zTree.getNodes();
    $.each(nodes, function (i) {
        //debugger
        nodes[i].nocheck = true;
        zTree.updateNode(nodes[i]);

    });
}
//初始化控件
$(document).ready(function () {
    var controls = $(this).find('input');
    controls.each(function () {
        if ($(this).attr("ctrlType") == "MultiPost") {
            $(this).MultiPostSelectCtrl(
              {
                  RootID: ''
              });
        }
    });
});
//
